#include "Device.h"
namespace android::wmark
{
    Device::Device(string dev, int openFlag):mDev(dev), mOpenFlag(openFlag)
    {
        openDev(openFlag);
    }
    Device::~Device()
    {
        if (mFd > 0)
        {
            close(mFd);
            mFd = -1;
        }
    }

    int Device::openDev(int openFlag)
    {
        int fd;
        if (mFd > 0)
        {
            return 0;
        }
        fd = open(mDev.c_str(), openFlag);
        if (fd == -1)
        {
            ALOGE("%s open failure: %s\n", mDev.c_str(), strerror(errno));
            return -1;
        }
        ALOGD("open %s success fd=%d!", mDev.c_str(), fd);
        mFd = fd;
        return 0;
    }

    int Device::getFd()
    {
        while (mFd < 0)
        {
            openDev(mOpenFlag);
        }

        return mFd;
    }

    int Device::ioctlDev(unsigned long cmd, void *msg)
    {
        m_mutex.lock();
        if (!msg)
        {
            ALOGE("%s %d msg==NULL fail!!!\n", __func__, __LINE__);
            return -1;
        }

        ALOGV("fd = %d cmd=%lu msg=%p", getFd(), cmd, msg);
        int ret = ioctl(getFd(), cmd, msg);
        if (ret)
        {
            ALOGE("%s %d fail!!! ret=%d %s\n", __func__, __LINE__, ret, strerror(errno));
        }
        m_mutex.unlock();
        return ret;
    }
}